import 'dart:io';

import 'package:flutter/services.dart';

import 'flkuaishou.dart';

typedef Success<T> = Function(T data);
typedef Fail = Function(int code, String msg);

class FlutterKuaiShouAuth {
  static late EventChannel _eventChannel;

  /**
   * 初始安卓
   */
  static Future<String> initPlatform(String appId, String universalLink) async {
    if (Platform.isAndroid) {
      return initPlatformAndroid();
    }else if(Platform.isIOS){
      return initPlatformIOS(appId, universalLink);
    }
    return "没有找到平台";
  }

  static Future<String> initPlatformAndroid() async {
    return await Flkuaishou.initPlatform() ?? 'Unknown platform message';
  }

  /**
   * 初始化苹果
   */
  static Future<String> initPlatformIOS(
      String appId, String universalLink) async {
    return await Flkuaishou.initPlatformIOS(appId, universalLink) ??
        'Unknown platform message';
  }

  /**
   * 请求授权
   */
  static Future KuaiShouOpenSDKAuthRequest(dynamic configState,
      {required Success success, required Fail fail}) async {
    String results = await Flkuaishou.KuaiShouOpenSDKAuthRequest(configState);
    print("授权返回：" + results);
    if (results.endsWith("success")) {
      if (Platform.isAndroid) {
        //安卓平台
        _eventChannel = const EventChannel('jldt_ks_flutter');
        _eventChannel.receiveBroadcastStream().listen((event) {
          print("event-1: $event");
          success(event);
        });
      } else if (Platform.isIOS) {
        // IOS 平台
        Flkuaishou.authUpdate.listen((event) {
          print("event-2: $event");
          success(event);
        });
      }
    } else {
      fail(-1, results);
    }
  }
}
